package com.gdufe.product.config;

import com.gdufe.common.handler.MyExtendAccessDeniedHandler;
import com.gdufe.common.handler.MyExtendAuthenticationEntryPointHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

@Configuration
@EnableResourceServer
public class ProductResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;
    @Autowired
    private MyExtendAuthenticationEntryPointHandler entryPointHandler;
    @Autowired
    private MyExtendAccessDeniedHandler deniedHandler;

    //资源服务ID
    private static final String RESOURCE_ID = "product";

    //令牌配置
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(tokenStore)
                .resourceId(RESOURCE_ID)
                .authenticationEntryPoint(entryPointHandler)
                .accessDeniedHandler(deniedHandler)
                .stateless(true);
    }

    //根据用户角色放行相应请求
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/product/admin/**").hasRole("ADMIN")
                .antMatchers("/product/user/**").hasRole("USER")
                .and().csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
